package RayTracing;

import java.util.ArrayList;


public class Sphere implements Shape{

	//########################## Global Variables ###################################
	double[] center = new double[3];
	double radius;
	int mtlIndex;
	
	
	//########################## Constructors ###################################
	public Sphere(){
		if (RayTracer.SHOW_LOG){ System.out.println("In Sphere Empty Constructor");}
		
	}
	
	
	public Sphere(String[] args){
		if (RayTracer.SHOW_LOG){ System.out.println("In Sphere Constructor");}
		
		center[0] = Double.parseDouble(args[0]);
		center[1] = Double.parseDouble(args[1]);
		center[2] = Double.parseDouble(args[2]);
		
		radius = Double.parseDouble(args[3]);
		mtlIndex = Integer.parseInt(args[4]);
		
	}
	
	public Sphere(double[] center, double radius, int mtlIndex){
		if (RayTracer.SHOW_LOG){ System.out.println("In Sphere Constructor");}
		
		this.center = center;
		this.radius = radius;
		this.mtlIndex = mtlIndex;
		
	}
	
	//########################## Shape Functions ###################################
	
	@Override
	public double[] getColor(Material mtl, Ray r, ArrayList<Lights> lgtList) {
		
		double[] N = Vector.createNormalizedVectorv(getCenter(), r.getP());
		return RayTracer.GlobalGetColor(mtl, r, lgtList, N);
	}


	@Override
	public double getT(Ray ray) {
		double[] V = ray.getV();
		double[] P0 = ray.getP0();
		
		double[] L = Vector.computeVectorSubstraction(getCenter() , P0);
		double t_ca = Vector.computeDotProduct(L, V);
		
		if (t_ca < 0)
			return -1;
		
		double d_pow = Vector.computeDotProduct(L, L) - Math.pow(t_ca, 2);
		double r_pow = Math.pow(getRadius(), 2);
		if (d_pow > r_pow){
			return -1;
		}
		
		
		double t_hc = Math.sqrt(r_pow - d_pow);
		
		if ((t_ca - t_hc) < 0)
			return t_ca + t_hc;
		
		if ((t_ca + t_hc) < 0)
			return t_ca - t_hc;
		
		return Math.min(t_ca - t_hc, t_ca + t_hc);
	}
	
	//########################## Getters and Setters ###################################
	
	public double[] getCenter() {
		return center;
	}


	public void setCenter(double[] center) {
		this.center = center;
	}


	public double getRadius() {
		return radius;
	}


	public void setRadius(double radius) {
		this.radius = radius;
	}

	@Override
	public int getMtlIndex() {
		return mtlIndex;
	}


	public void setMtlIndex(int mtlIndex) {
		this.mtlIndex = mtlIndex;
	}



}
